<template>
  <div class="container">
    <div class="container_page">
      <page-header :title="$t('profile_profile')"></page-header>
      <div class="list">
        <div class="item">
          <div class="left">
            <div class="title">{{ $t("menu_userID") }}</div>
          </div>
          <div class="right">{{ info.uid | stateUID }}</div>
        </div>
        <div class="divider"></div>
        <!-- <div class="item" @click="isShowDateTimeDialog = true">
          <div class="left">
            <div class="title">{{ $t("profile_birthday") }}</div>
            <div class="sub_title">
              {{ formateDirthday(info.birthday) || "YYYY-MM-DD" }}
            </div>
          </div>
          <div class="right">
            <img :src="require('@/assets/img/user/faq_ic_right@2x.png')" />
          </div>
        </div> -->
        <!-- <div class="divider"></div> -->
        <!-- <div class="item" @click="showSexDialog">
          <div class="left">
            <div class="title">{{ $t("profile_gender") }}</div>
            <div class="sub_title">
              {{ getSexValue(info.sex) || $t("profile_select") }}
            </div>
          </div>
          <div class="right">
            <img :src="require('@/assets/img/user/faq_ic_right@2x.png')" />
          </div>
        </div>
        <div class="divider"></div> -->
        <div class="item" @click="showEmailDialog">
          <div class="left">
            <div class="title">{{ $t("login_email") }}</div>
            <div class="sub_title">{{ info.email | stateFormats }}</div>
          </div>
          <div class="right" v-if="!info.email">
            <img :src="require('@/assets/img/user/faq_ic_right@2x.png')" />
          </div>
        </div>
        <div class="divider"></div>
        <div class="item" @click.stop.prevent="showPhoneDialog">
          <div class="left">
            <div class="title">{{ $t("login_phoeNumber") }}</div>
            <div class="sub_title" v-if="info.phone">
              (+{{ info.code }}) {{ info.phone | stateFormats }}
            </div>
            <div class="sub_title" v-else>
              {{ info.phone | stateFormats }}
            </div>
          </div>
          <div class="right" v-if="!info.phone">
            <img :src="require('@/assets/img/user/faq_ic_right@2x.png')" />
          </div>
        </div>
        <div class="divider"></div>
        <div class="item" v-if="info.apple || info.google">
          <div class="left">
            <div class="title">{{ info.apple ? $t('info_appleLogin') : $t('info_googleLogin') }}</div>
            <div class="sub_title">
              {{ $t('info_authorized') }}
            </div>
          </div>
        </div>
        <div class="divider" v-if="info.apple || info.google"></div>        
      </div>
      <!-- 时间选择 -->
      <van-popup v-model="isShowDateTimeDialog" position="bottom" round>
        <div style="width: 100%;">
          <van-datetime-picker
            v-model="currentDate"
            :min-date="minDate"
            :max-date="maxDate"
            type="date"
            title="DD/MM/YYYY"
            :columns-order="['day', 'month', 'year']"
            :confirm-button-text="$t('home_confirm')"
            :cancel-button-text="$t('profile_cancel')"
            @confirm="saveBirthday"
            @cancel="isShowDateTimeDialog = false"
          />
        </div>
      </van-popup>
      <!-- 性别 -->
      <van-dialog v-model="isShowSexDialog" :showConfirmButton="false">
        <div class="title">{{ $t("profile_gender") }}</div>
        <div class="sexBox">
          <div class="item" v-for="item in sexList" @click="chooseSex(item)" :key="item">
            <span>{{ getSexValue(item) }}</span>
            <img
              v-if="item === ruleForm.sex"
              :src="require('@/assets/img/user/profile_ic_selected.svg')"
            />
          </div>
        </div>
        <div class="btns">
          <div class="btn flex_center" @click="cancelForm">
            {{ $t("profile_cancel") }}
          </div>
          <div class="btn flex_center" @click="saveSex">
            {{ $t("invite_save") }}
          </div>
        </div>
      </van-dialog>
      <!-- 邮箱 -->
      <van-dialog v-model="isShowEmailDialog" :showConfirmButton="false">
        <el-form
          :model="ruleForm"
          :rules="emailRules"
          ref="eamilFormRef"
          label-position="top"
          class="el_form"
        >
          <div class="title">{{ $t("login_email") }}</div>
          <el-form-item prop="email">
            <el-input
              v-model="ruleForm.email"
              type="email"
              :placeholder="$t('toast_requiredEmail')"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="msgCode">
            <el-input
              v-model="ruleForm.msgCode"
              type="tel"
              maxlength="4"
              :placeholder="$t('login_verificationCode')"
              clearable
              class="from_item_msgcode"
              @input="ruleForm.msgCode = formateNumber($event)"
            >
            </el-input>
            <div class="msg_code">
              <van-button
                type="info"
                size="large"
                :disabled="vertiyCode.email.isLoading"
                @click.stop.prevent="sendMsgCode('email')"
              >
                {{
                  vertiyCode.email.isLoading
                    ? vertiyCode.email.num + "s"
                    : $t("login_get")
                }}
              </van-button>
            </div>
          </el-form-item>
          <div class="btns">
            <div class="btn flex_center" @click="cancelForm">
              {{ $t("profile_cancel") }}
            </div>
            <div class="btn flex_center" @click="submitForm('eamilFormRef')">
              {{ $t("invite_save") }}
            </div>
          </div>
        </el-form>
      </van-dialog>

      <!-- 手机号 -->
      <van-dialog v-model="isShowPhoneDialog" :showConfirmButton="false">
        <el-form
          :model="ruleForm"
          :rules="phoneRules"
          ref="phoneFormRef"
          label-position="top"
          class="el_form"
        >
          <div class="title">{{ $t("login_phoeNumber") }}</div>
          <el-form-item prop="phone">
            <el-input
              v-model="ruleForm.phone"
              type="tel"
              maxlength="15"
              :placeholder="$t('profile_enterPhoneNum')"
              clearable
            >
              <template slot="prepend">
                <div @click="isShowCountryCode = true">
                  + {{ ruleForm.code }}
                  <i
                    class="el-icon-arrow-down el-icon--right"
                    style="margin-left:10px;"
                  ></i>
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="msgCode">
            <el-input
              v-model="ruleForm.msgCode"
              type="tel"
              maxlength="4"
              :placeholder="$t('login_verificationCode')"
              clearable
              class="from_item_msgcode"
              @input="ruleForm.msgCode = formateNumber($event)"
            >
            </el-input>
            <div class="msg_code">
              <van-button
                type="info"
                size="large"
                :disabled="vertiyCode.phone.isLoading"
                @click.stop.prevent="sendMsgCode('phone')"
              >
                {{
                  vertiyCode.phone.isLoading
                    ? vertiyCode.phone.num + "s"
                    : $t("login_get")
                }}
              </van-button>
            </div>
          </el-form-item>
          <div class="btns">
            <div class="btn flex_center" @click="cancelForm">
              {{ $t("profile_cancel") }}
            </div>
            <div class="btn flex_center" @click="submitForm('phoneFormRef')">
              {{ $t("invite_save") }}
            </div>
          </div>
        </el-form>
      </van-dialog>
      <country-code
        v-model="isShowCountryCode"
        @select="chooseCountryCode"
      ></country-code>
    </div>
  </div>
</template>

<script>
import $api from "@/assets/js/api/index";
import $login from "@/assets/js/api/login";
import share from "@/mixins/share";
export default {
  mixins: [share],
  data() {
    var validateCode = (rule, value, callback) => {
      const codeReg = /^[0-9]{4}$/;
      if (!value) {
        return callback(new Error(this.$t("toast_requiredCode")));
      }
      setTimeout(() => {
        if (codeReg.test(value)) {
          callback();
        } else {
          callback(new Error(this.$t("toast_validCode")));
        }
      }, 100);
    };
    const validatePhone = (rule, value, callback) => {
      const phoneReg = /^[0-9]{8,15}$/;
      if (!value) {
        return callback(new Error(this.$t("toast_requiredPhone")));
      }
      setTimeout(() => {
        if (phoneReg.test(value)) {
          callback();
        } else {
          callback(new Error(this.$t("toast_validPhone")));
        }
      }, 100);
    };
    const validateEmail = (rule, value, callback) => {
      const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!value) {
        return callback(new Error(this.$t("toast_requiredEmail")));
      }
      setTimeout(() => {
        if (emailReg.test(value)) {
          callback();
        } else {
          callback(new Error(this.$t("toast_validEmail")));
        }
      }, 100);
    };
    return {
      isShowDateTimeDialog: false,
      isShowSexDialog: false,
      isShowEmailDialog: false,
      isShowPhoneDialog: false,
      isShowCountryCode: false,
      currentDate: new Date(),
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(),
      sexList: [0, 1, 2],
      ruleForm: {
        msgCode: "",
        phone: "",
        email: "",
        sex: "",
        code: "",
        birthday: ""
      },
      emailRules: {
        msgCode: [{ validator: validateCode, trigger: "blur" }],
        email: [{ validator: validateEmail, trigger: "blur" }]
      },
      phoneRules: {
        msgCode: [{ validator: validateCode, trigger: "blur" }],
        phone: [{ validator: validatePhone, trigger: "blur" }]
      },
      info: {
        id: "",
        phone: "",
        email: "",
        sex: "",
        birthday: "",
        code: ""
      },
      vertiyCode: localStorage.getItem("vertiyCode")
        ? JSON.parse(localStorage.getItem("vertiyCode"))
        : {
            email: {
              num: 60,
              isLoading: false,
              timer: null,
              timetamp: 0
            },
            phone: {
              num: 60,
              isLoading: false,
              timer: null,
              timetamp: 0
            }
          }
    };
  },
  created() {
    this.getLang();
  },
  methods: {
    formateNumber(value) {
      if (!value) return;
      return value.replace(/[^\d]/g, "");
    },
    chooseCountryCode(val) {
      this.ruleForm.code = val;
      localStorage.setItem("country_code", this.ruleForm.code);
    },
    showEmailDialog() {
      if (this.info.email) {
        return;
      }
      this.isShowEmailDialog = true;
      //  this.ruleForm.email = localStorage.getItem("user_email") || "";
      this.ruleForm.email = "";
      this.$nextTick(() => {
        this.sendMsgCode("email", "auto");
        // this.$refs["eamilFormRef"].clearValidate();
      });
    },
    showPhoneDialog() {
      if (this.info.phone) {
        return;
      }
      this.isShowPhoneDialog = true;
      // this.ruleForm.phone = localStorage.getItem("user_phone") || "";
      this.ruleForm.phone = "";
      this.ruleForm.code =
        localStorage.getItem("country_code") ||
        localStorage.getItem("code") ||
        "1";
      this.$nextTick(() => {
        this.sendMsgCode("phone", "auto");
        // this.$refs["phoneFormRef"].clearValidate();
      });
    },
    showSexDialog() {
      this.isShowSexDialog = true;

      this.ruleForm.sex = this.info.sex;
    },
    saveSex() {
      this.updateDetails(this.ruleForm);
    },
    sendMsgCode(type, flag) {
      let param = null;
      let formRef = "";
      if (type == "email") {
        param = {
          email: this.ruleForm.email || "",
          scene: 3
        };
        formRef = "eamilFormRef";
      }
      if (type == "phone") {
        param = {
          phone: this.ruleForm.phone || "",
          scene: 2,
          code: this.ruleForm.code
        };
        formRef = "phoneFormRef";
      }
      this.checkIsSendCode(type, param, flag, formRef);
      // this.$refs[formRef].validateField(type, valid => {
      //   if (!valid) {
      //     localStorage.setItem("user_" + type, this.ruleForm[type]);
      //   }
      // });
    },
    // 检测是否发送验证码
    checkIsSendCode(type, param, flag, formRef) {
      const isOver60 = Date.now() - this.vertiyCode[type].timetamp > 60000;
      if (isOver60) {
        this.vertiyCode[type].isLoading = false;
        this.vertiyCode[type].num = 60;
        if (flag == "auto") return;
      } else {
        // this.vertiyCode[type].num = parseInt(
        //   (Date.now() - this.vertiyCode[type].timetamp) / 1000
        // );
        this.startCodeCountdown(type);
        return;
      }
      if (this.vertiyCode[type].isLoading) return;
      this.$refs[formRef].validateField(type, valid => {
        if (!valid) {
          $login.getLoginCode(param).then(res => {
            if (res.code != "0") {
              this.global.toast(res.message);
              return;
            }
            this.vertiyCode[type].timetamp = Date.now();
            this.startCodeCountdown(type);
          });
        }
      });
    },
    // 开始倒计时
    startCodeCountdown(type) {
      this.vertiyCode[type].isLoading = true;
      clearInterval(this.vertiyCode[type].timer);

      this.vertiyCode[type].timer = setInterval(() => {
        localStorage.setItem("vertiyCode", JSON.stringify(this.vertiyCode));
        if (this.vertiyCode[type].num <= 0) {
          clearInterval(this.vertiyCode[type].timer);
          this.vertiyCode[type].isLoading = false;
          this.vertiyCode[type].num = 60;
          this.vertiyCode[type].timetamp = 0;
          return;
        }
        this.vertiyCode[type].num--;
      }, 1000);
    },
    saveBirthday(value) {
      // console.log(this.$moment(value).format("MMM/DD/YYYY"));
      // console.log(this.$moment(value).month());
      this.ruleForm.birthday = this.$moment(value).format("MM/DD/YYYY");
      this.updateDetails(this.ruleForm);
    },
    chooseSex(item) {
      this.ruleForm.sex = item;
    },
    cancelForm() {
      this.isShowEmailDialog = false;
      this.isShowPhoneDialog = false;
      this.isShowSexDialog = false;
      this.isShowDateTimeDialog = false;
      this.ruleForm = this.$options.data.call(this).ruleForm;
    },
    async updateDetails(params) {
      let tmpParam = { ...params };
      Object.keys(tmpParam).forEach(key => {
        if (!tmpParam[key]) {
          if (tmpParam[key] === 0) return;
          delete tmpParam[key];
        }
      });
      const res = await $api.user.updateDetails(tmpParam);
      if (res.code != "0") {
        this.global.toast(res.message);
        return;
      }
      Object.keys(tmpParam).forEach(key => {
        this.info[key] = tmpParam[key];
      });
      localStorage.setItem("userInfo", JSON.stringify(this.info));
      this.cancelForm();
      this.getUserInfo();
      return res;
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.updateDetails(this.ruleForm).then(res => {
            if (res.code != 0) {
              this.global.toast(res.message);
              return;
            }
            this.cancelForm();
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    cancelPhoneForm() {
      this.isShowPhoneDialog = false;
      this.ruleForm = this.$options.data.call(this).ruleForm;
    },
    getUserInfo() {
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      if (!userInfo) {
        this.$router.replace("/login");
        return;
      }
      this.info = userInfo;
    },
    getSexValue(val) {
      const sexMap = {
        0: "profile_female",
        1: "profile_male",
        2: "profile_secret",
        3: "home_other"
      };
      if (val == 3) return "";
      if (sexMap[val]) {
        return this.$t(sexMap[val]);
      }
      return this.$t("profile_secret");
    },
    formateDirthday(value) {
      if (!value) return "";
      // return this.$moment(value, "MMM/DD/YYYY").toDate();
      return this.$moment(value, "MM/DD/YYYY").format("YYYY-MM-DD");
    }
  },
  mounted() {
    this.getUserInfo();
  },
  computed: {}
};
</script>
<style scoped lang="scss">
.container_page {
  margin: 0;
  background-color: #f5f5f7;
  width: 100%;
  flex: 1;
  box-sizing: border-box;
}
.divider {
  height: 4px;
  background-color: #f0f0f2;
}
.list {
  padding-top: 10px;
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 56px;
    background-color: #f5f5f7;
    .title {
      font-size: 14px;
      font-weight: 600;
      color: #383838;
    }
    .sub_title {
      margin-top: 4px;
      font-size: 12px;
      font-weight: 500;
      color: #66666b;
    }
    .left {
      flex: 1;
    }
    .right {
      font-size: 14px;
      font-weight: 500;
      color: #383838;
      img {
        width: 44px;
        height: 44px;
        margin-right: -22px;
      }
    }
  }
}
.sexBox {
  background-color: var(--card-color);
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 52px;
    padding: 0 var(--gap);
    border-bottom: #eeeef5 1px solid;
    &:nth-last-child(1) {
      border: none;
    }
    span {
      font-size: 14px;
      color: #383838;
    }
    img {
      width: 20px;
      height: 20px;
    }
  }
}

.from_item_msgcode {
  padding-right: 96px !important;
  box-sizing: border-box;
}
.msg_code {
  position: absolute;
  right: 8px;
  top: 0;

  height: 36px;
  .van-button {
    height: inherit;
    padding: 0 12px;
    border-radius: 6px;
    font-size: 12px;
  }
}
</style>
